@file:Suppress("DEPRECATION")

package com.jackiepenghe.huaweimqttlibrary

import android.annotation.SuppressLint
import android.content.Context
import android.content.IntentFilter
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.huaweicloud.sdk.iot.device.IoTDevice
import com.huaweicloud.sdk.iot.device.client.requests.CommandRsp
import com.huaweicloud.sdk.iot.device.client.requests.DeviceMessage
import com.huaweicloud.sdk.iot.device.client.requests.ServiceProperty
import com.huaweicloud.sdk.iot.device.constant.IotDeviceIntent
import com.jackiepenghe.huaweimqttlibrary.listeners.*
import com.jackiepenghe.huaweimqttlibrary.receivers.IotDeviceBroadcastReceiver

@Suppress("unused")
@SuppressLint("StaticFieldLeak")
object MqttManager {

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 属性声明
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /* * * * * * * * * * * * * * * * * * * 常量属性 * * * * * * * * * * * * * * * * * * */

    /**
     *  接收Huawei IOT 广播的接收者（所有IOT事件都通过广播通知）
     */
    private val iotDeviceBroadcastReceiver = IotDeviceBroadcastReceiver()

    /* * * * * * * * * * * * * * * * * * * 可变属性 * * * * * * * * * * * * * * * * * * */

    /**
     * 上下文
     */
    private var context: Context? = null

    /**
     * Huawei IOT 设备实例
     */
    private var device: IoTDevice? = null

    fun init(context: Context) {
        if (this.context != null) {
            return
        }
        this.context = context
        val intentFilter = IntentFilter()
        //设备连接状态
        intentFilter.addAction(IotDeviceIntent.ACTION_IOT_DEVICE_CONNECT)
        //设备属性上报结果
        intentFilter.addAction(IotDeviceIntent.ACTION_IOT_DEVICE_PROPERTIES_REPORT)
        //消息上报（上传）
        intentFilter.addAction(IotDeviceIntent.ACTION_IOT_DEVICE_SYS_MESSAGES_UP)
        //平台查询设备属性
        intentFilter.addAction(IotDeviceIntent.ACTION_IOT_DEVICE_SYS_PROPERTIES_GET)
        //平台设置设备属性
        intentFilter.addAction(IotDeviceIntent.ACTION_IOT_DEVICE_SYS_PROPERTIES_SET)
        //平台消息下发
        intentFilter.addAction(IotDeviceIntent.ACTION_IOT_DEVICE_SYS_MESSAGES_DOWN)
        //平台命令下发
        intentFilter.addAction(IotDeviceIntent.ACTION_IOT_DEVICE_SYS_COMMANDS)
        //注册广播
        LocalBroadcastManager.getInstance(context)
            .registerReceiver(iotDeviceBroadcastReceiver, intentFilter)
    }

    fun connect(serverAddress: String, deviceId: String, deviceSecret: String) {
        device?.close()
        val serverUri = "tcp://${serverAddress}:1883"
        Log.w("TAG", "connect: serverUrl = $serverUri")
        device =
            IoTDevice(
                context,
                serverUri,
                deviceId,
                deviceSecret
            )
        device?.init()
    }

    /**
     * 上报设备属性
     */
    fun reportProperties(serviceProperties: ArrayList<ServiceProperty>) {
        val ioTDevice = device
        if (ioTDevice == null) {
            iotDeviceBroadcastReceiver.onPropertyReportListener?.reportFailed("device null")
            return
        }
        ioTDevice.client?.reportProperties(serviceProperties)
    }

    fun respondCommand(requestId: String, commandRsp: CommandRsp) {
        val ioTDevice = device
        if (ioTDevice == null) {
            iotDeviceBroadcastReceiver.onRespondCommandListener?.responseFailed("device null")
            return
        }
        //设备响应平台命令执行结果
        ioTDevice.client?.respondCommand(requestId, commandRsp)
    }

    fun closeDevice() {
        device?.close()
        device = null
    }

    /**
     * 上报（上传）消息
     */
    fun reportDeviceMessage(deviceMessage: DeviceMessage) {
        val ioTDevice = device
        if (ioTDevice == null) {
            iotDeviceBroadcastReceiver.onPropertyReportListener?.reportFailed("device null")
            return
        }
        ioTDevice.client?.reportDeviceMessage(deviceMessage)
    }

    fun setOnDeviceConnectListener(onDeviceConnectListener: OnDeviceConnectListener?) {
        iotDeviceBroadcastReceiver.onDeviceConnectListener = onDeviceConnectListener
    }

    fun setOnPropertyUploadListener(onPropertyReportListener: OnPropertyReportListener?) {
        iotDeviceBroadcastReceiver.onPropertyReportListener = onPropertyReportListener
    }

    fun setOnDeviceMessageUpListener(onDeviceMessageUpListener: OnDeviceMessageUpListener?) {
        iotDeviceBroadcastReceiver.onDeviceMessageUpListener = onDeviceMessageUpListener
    }

    fun setOnDevicePropertyGetListener(onDevicePropertyGetListener: OnDevicePropertyGetListener?) {
        iotDeviceBroadcastReceiver.onDevicePropertyGetListener = onDevicePropertyGetListener
    }

    fun setOnDevicePropertySetListener(onDevicePropertySetListener: OnDevicePropertySetListener?) {
        iotDeviceBroadcastReceiver.onDevicePropertySetListener = onDevicePropertySetListener
    }

    fun setOnDeviceMessageDownListener(onDeviceMessageDownListener: OnDeviceMessageDownListener?) {
        iotDeviceBroadcastReceiver.onDeviceMessageDownListener = onDeviceMessageDownListener
    }

    fun setOnDeviceCommandListener(onDeviceCommandListener:OnDeviceCommandListener?){
        iotDeviceBroadcastReceiver.onDeviceCommandListener = onDeviceCommandListener
    }

    fun setOnRespondCommandListener(onRespondCommandListener: OnRespondCommandListener?) {
        iotDeviceBroadcastReceiver.onRespondCommandListener = onRespondCommandListener
    }
}